package sen.queryUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 生成表单域封装类的工厂类
 * @author sen
 */
public class ConditionalFactory {

	private ConditionalFactory(){}
	/**
	 * 据原始表单map创建表单域封装类的List集合
	 * @param param : 原始表单的map
	 * @return
	 */
	public List<Cond> createConditional(Map<String, String> param) {
		List<Cond> conds = new ArrayList<Cond>();
		if(null == param || param.isEmpty()) {
			return conds;
		}
		
		for(Iterator<String> it = param.keySet().iterator(); it.hasNext();) {
			String k = it.next();//表单名=条件关系符#真正的表单名，如：0#name
			String v = param.get(k);

			int relator = Conditional.EQ;
			String[] tep = k.split("#");
			if(tep.length>2) {
				throw new RuntimeException("表单名除前缀外不能有#！");
			}
			if(tep.length>1) {//如果能被#劈开，说明附带有关系符
				try {
					relator = Integer.parseInt(tep[0]);
				} catch (NumberFormatException e) {
				}
				k = tep[1];
			}
			
			Conditional cond = new Conditional(k, v, relator);
			
			conds.add(cond);
		}
		return conds;
	}
	
	/**
	 * 据原始表单map创建表单域封装类的List集合
	 * @param param : 原始表单的map
	 * @return
	 */
	public Map<String, Conditional> createConditionalToMap(Map<String, String> param) {
		Map<String, Conditional> conds = new HashMap<String, Conditional>();
		if(null == param || param.isEmpty()) {
			return conds;
		}
		
		for(Iterator<String> it = param.keySet().iterator(); it.hasNext();) {
			String k = it.next();//表单名=条件关系符#真正的表单名，如：0#name
			String v = param.get(k);

			int relator = Conditional.EQ;
			String[] tep = k.split("#");
			if(tep.length>2) {
				throw new RuntimeException("表单名除前缀外不能有#！");
			}
			if(tep.length>1) {//如果能被#劈开，说明附带有关系符
				try {
					relator = Integer.parseInt(tep[0]);
				} catch (NumberFormatException e) {
				}
				k = tep[1];
			}
			
			Conditional cond = new Conditional(k, v, relator);
			
			conds.put(k, cond);
		}
		return conds;
	}
	
	private static ConditionalFactory condFact = null;
	public static ConditionalFactory getInstance() {
		if(null == condFact){
			condFact = new ConditionalFactory();
		}
		return condFact;
	}
}